package com.erbao.dp.itrator;

/**
 * @author CaoBaoYin
 * @since 2021/9/18 18:33
 */
public class ArrayList_<E> implements Collection_<E> {

    private Object[] objs;
    private int size;

    public ArrayList_() {
        objs = new Object[5];
    }

    @Override
    public boolean add(E e) {
        ensureCapacity();

        objs[size ++] = e;

        return true;
    }

    public boolean remove(E e) {
        if (e == null) {
            for (int i = 0; i < size; i++) {
                if (objs[i] == null) {
                    int numMoved = size - i - 1;
                    System.arraycopy(objs, i+1, objs, i, numMoved);
                    objs [-- size] = null;
                    i--;
                }
            }
        } else {
            for (int i = 0; i < size; i++) {
                if (objs[i].equals(e)) {
                    int numMoved = size - i - 1;
                    System.arraycopy(objs, i+1, objs, i, numMoved);
                    objs [-- size] = null;
                    i--;// 移除元素后遍历角标不增长
                }
            }
        }
        return true;
    }

    private void ensureCapacity() {
        if (size == objs.length) {
            Object[] temp = new Object[objs.length * 2];

            System.arraycopy(objs, 0, temp, 0, objs.length);

            objs = temp;
        }
    }

    @Override
    public int size() {
        return 0;
    }

    @Override
    public Iterator_<E> iterator() {
        return new ArrayListIterator<E>();
    }

    public boolean isEmpty() {
        return size == 0;
    }

    private class ArrayListIterator<E> implements Iterator_<E> {
        private int index;

        public ArrayListIterator() {
        }

        @Override
        public boolean hasNext() {
            return index < size;
        }

        @Override
        public E next() {
            return (E) objs[index++];
        }
    }
}
